﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Caching;

namespace Xpus.Web.Common
{
	/// <summary>
	/// 为App_Data目录中的配置提供缓存。
	/// </summary>
	/// <typeparam name="T">缓存数据的类型。</typeparam>
	public class XpusAppDataCache<T>
	{
		/// <summary>
		/// 将数据放到缓存中。
		/// </summary>
		/// <param name="virtualPath">数据文件的虚拟路径。</param>
		/// <param name="data">待缓存的数据。</param>
		public static void Set(string virtualPath, T data)
		{
			if (virtualPath == null)
				throw new ArgumentNullException();

			string path = HttpContext.Current.Server.MapPath(virtualPath);
			CacheDependency depend = new CacheDependency(path);
			HttpContext.Current.Cache.Insert(virtualPath, data, depend);
		}

		/// <summary>
		/// 从缓存中取出数据。
		/// </summary>
		/// <param name="virtualPath">数据文件的虚拟路径。</param>
		/// <returns>与数据文件相关的数据。如果没有或缓存失效，返回T的默认值。</returns>
		public static T Get(string virtualPath)
		{
			object data = HttpContext.Current.Cache[virtualPath];
			if(data == null)
				return default(T);
			else
				return (T)data;
		}
	}
}
